package com.haoyun.mirage.user.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haoyun.common.constant.CommonConstant;
import com.haoyun.common.core.Result;
import com.haoyun.mirage.user.model.entity.SysDept;
import com.haoyun.mirage.user.model.vo.DeptTree;
import com.haoyun.mirage.user.model.vo.DeptVO;
import com.haoyun.mirage.user.service.ISysDeptService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author twg
 * @since 2018-05-30
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController {
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return SysDept
     */
    @GetMapping("/{id}")
    public DeptVO get(@PathVariable Long id) {
        DeptVO deptVO = new DeptVO();
        SysDept dept = sysDeptService.selectById(id);
        BeanUtil.copyProperties(dept,deptVO);
        return deptVO;
    }


    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public List<DeptTree> getTree() {
        SysDept condition = new SysDept();
        condition.setIsDeleted(CommonConstant.STATUS_NORMAL);
        return sysDeptService.selectListTree(new EntityWrapper<SysDept>(condition));
    }

    /**
     * 添加
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PostMapping
    public Result<String> add(@RequestBody @Valid DeptVO dept, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return Result.buildErrorResult(fieldError.getDefaultMessage());
        }
        SysDept sysDept = new SysDept();
        BeanUtil.copyProperties(dept,sysDept);
        sysDeptService.insertDept(sysDept);
        return Result.buildSuccessResult("添加成功");
    }

    /**
     * 删除
     *
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Long id) {
        return sysDeptService.deleteDeptById(id);
    }

    /**
     * 编辑
     *
     * @param deptVO 实体
     */
    @PutMapping
    public Result<String> edit(@RequestBody @Valid DeptVO deptVO,BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return Result.buildErrorResult(fieldError.getDefaultMessage());
        }
        SysDept sysDept = new SysDept();
        BeanUtil.copyProperties(deptVO,sysDept);
        sysDeptService.updateDeptById(sysDept);
        return Result.buildSuccessResult("修改成功");
    }

}

